//
//  BLTimeAxisView.m
//  BLTimeAxis
//
//  Created by dg on 2025/4/18.
//

#import "BLTimeAxisView.h"
#import "BLTimeAxisData.h"
#import "BLTimeAxisRenderer.h"

@implementation BLTimeAxisView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame: frame]) {
        // 必须设置一种颜色，不然drawRect:绘制的图像会重叠
        [self setBackgroundColor:[UIColor whiteColor]];
        
        [self setRendererClass:[BLTimeAxisRenderer class]];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    if ([self.rendererClass isKindOfClass:[BLTimeAxisRenderer class]]) return;
    
    id<BLTimeAxisVisitor> renderVisitor = [[self.rendererClass alloc] initWithViewSize:rect.size context:context];
    
    // 先绘制UI    // DHTimeAxisBackground     DHTimeAxisRule  DHTimeAxisBaseLine   DHTimeAxisDigitalDivision
    for(id<BLTimeAxisComponent> axis in _appearanceArray) {
        [axis acceptVisitor:renderVisitor];
    }
    
    // 再绘制段数据
    for(id<BLTimeAxisComponent> axis in _dataArray) {
        [axis acceptVisitor:renderVisitor];
    }
}

- (void)refreshViewInMainThread {
    __weak typeof(self) weakself = self;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakself setNeedsDisplay];
    });
}

- (void)setDataArray:(NSArray<BLTimeAxisData *> *)dataArray {
    _dataArray = dataArray;
    
    [self refreshViewInMainThread];
}

- (void)setAppearanceArray:(NSArray<id<BLTimeAxisComponent>> *)appearanceArray {
    _appearanceArray = appearanceArray;
    
    [self refreshViewInMainThread];
}

@end
